import {
    Component, OnInit, Input, ViewChild,
    ElementRef, Output, EventEmitter, Renderer
} from '@angular/core';
import { UploadFileInfo } from './upload-file-info.class';

const MAX_UPLOAD_FILE_SIZE = 10 * 1024 * 1024; // 10MB


@Component({
    selector: 'file-uploader',
    styleUrls: ['file-uploader.component.scss'],
    templateUrl: 'file-uploader.component.html'
})
export class FilUploaderComponent implements OnInit {
    @Input() public url: string;
    @Input() public inputName: string;
    @Output() public uploadend: EventEmitter<UploadFileInfo> = new EventEmitter<UploadFileInfo>();
    @ViewChild('fileInput') fileInput: ElementRef;
    public errorMsg: string;
    public percentage: number;
    constructor(private _renderer: Renderer) { }

    ngOnInit() { }

    public selectFile() {
        this.fileInput.nativeElement.click();
        this.percentage = 0;
        this.errorMsg = null;
    }

    public uploadFile(event) {
        let files: File[] = event.srcElement.files;
        if (files.length > 0) {
            let file: File = files[0];
            if (file.size > MAX_UPLOAD_FILE_SIZE) {
                this.errorMsg = '上传文件大小不得大于10MB';
                return;
            }

            let xhr = new XMLHttpRequest();
            let self = this;

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    let resp = JSON.parse(xhr.responseText);
                    if (resp.status === 'success') {
                        let fileInfo: UploadFileInfo = <UploadFileInfo> resp.data[0];
                        fileInfo.originName = file.name;
                        self.uploadend.emit(fileInfo);
                    } else {
                        self.errorMsg = resp.data;
                    }
                }
            };

            xhr.upload.addEventListener('progress', function(e: any) {
                if (e.lengthComputable) {
                    self.percentage = Math.round((e.loaded * 100) / e.total);
                }
            }, false);

            let fd = new FormData();
            fd.append(this.inputName, file);
            xhr.open('POST', this.url, true);
            xhr.send(fd);
        }
    }
}
